package com.eagletsoft.mmproj.ui;

import java.util.HashMap;
import java.util.List;

import com.eagletsoft.mmproj.model.MessageModel;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;

public class MyPageAdapter extends PagerAdapter{

	private Context context;
	private List<MessageModel> messages;
	private int numOfPage;
	private HashMap<Integer, PageLayoutView> pageHashMap; 
	
	public MyPageAdapter(Context context, List<MessageModel> messages) {
		this.context = context;
		this.messages = messages;
		numOfPage = this.messages.size()/5;
		if(this.messages.size()%5>0)
			numOfPage++;
		pageHashMap = new HashMap<Integer, PageLayoutView>(); 
	}
	
	@Override  
    public Object instantiateItem(View container, int position) {
		PageLayoutView layoutView = null;
		if(pageHashMap.containsKey(position)){ 
			layoutView = pageHashMap.get(position);
		} else {
			layoutView = new PageLayoutView(context);
			int rangeFrom = position*5;
			int rangeTo = (position+1)*5;
			if(rangeTo > (messages.size()))
				rangeTo = messages.size();
			Log.i("TAG", "RangeFrom="+rangeFrom);
			Log.i("TAG", "rangeTo="+rangeTo);
			List<MessageModel> showingMessages = messages.subList(rangeFrom, rangeTo);
			layoutView.setData(showingMessages);
			pageHashMap.put(position, layoutView);
			 ((ViewPager) container).addView(layoutView);  
		}
		return layoutView; 
		
	}
	
	@Override  
    public void destroyItem(View container, int position, Object object) {  
        
    }  

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return numOfPage;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		// TODO Auto-generated method stub
		return view == object; 
	}

}
